package com.action.gulimall.product.service.impl;

import com.action.common.utils.R;
import com.action.gulimall.product.entity.SkuImagesEntity;
import com.action.gulimall.product.entity.SpuInfoDescEntity;
import com.action.gulimall.product.fegin.SeckillFeignService;
import com.action.gulimall.product.service.AttrGroupService;
import com.action.gulimall.product.service.SkuImagesService;
import com.action.gulimall.product.service.SpuInfoDescService;
import com.action.gulimall.product.vo.SeckillSkuVo;
import com.action.gulimall.product.vo.SkuItemSaleAttrVo;
import com.action.gulimall.product.vo.SkuItemVo;
import com.action.gulimall.product.vo.SpuItemAttrGroupVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.action.gulimall.product.dao.SkuInfoDao;
import com.action.gulimall.product.entity.SkuInfoEntity;
import com.action.gulimall.product.service.SkuInfoService;
import com.action.common.utils.PageUtils;
import com.action.common.utils.Query;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@Slf4j
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    ThreadPoolExecutor globalExecutor;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    AttrGroupService attrGroupService;
    @Autowired
    SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key) && !"0".equalsIgnoreCase(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("sku_id", key).or().like("sku_name", key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }

        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            queryWrapper.ge("price", min);
        }

        String max = (String) params.get("max");

        if (!StringUtils.isEmpty(max)) {
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                if (bigDecimal.compareTo(BigDecimal.ZERO) == 1) {
                    queryWrapper.le("price", max);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // key:
        // catelogId: 225
        // brandId: 9
        // min: 0
        // max: 0

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkuInfosBySpuId(Long spuId) {
        return this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        log.debug("获取skuId={}的详情信息",skuId);
        SkuItemVo skuItemVo = new SkuItemVo();
        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            log.debug("获取skuId={}的基本信息",skuId);
            //1、sku基本信息的获取  pms_sku_info
            SkuInfoEntity skuInfoEntity = this.getById(skuId);
            skuItemVo.setInfo(skuInfoEntity);
            return skuInfoEntity;
        }, globalExecutor);

        CompletableFuture<Void> future1 = skuInfoFuture.thenAcceptAsync((skuInfoEntity) -> {
            //3、获取spu的销售属性组合  需要spuId
            log.debug("获取spuId={}的销售属性组合",skuInfoEntity.getSpuId());
            List<SkuItemSaleAttrVo> skuItemSaleAttrVos = getAllSaleAttrBySpuId(skuInfoEntity.getSpuId());
            skuItemVo.setSaleAttr(skuItemSaleAttrVos);
        }, globalExecutor);

        CompletableFuture<Void> future2 = skuInfoFuture.thenAcceptAsync((skuInfoEntity) -> {
            //4、获取spu的介绍    pms_spu_info_desc   需要spuId
            log.debug("获取spuId={}的商品描述信息",skuInfoEntity.getSpuId());
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(skuInfoEntity.getSpuId());
            skuItemVo.setDesc(spuInfoDescEntity);
        }, globalExecutor);

        CompletableFuture<Void> future3 = skuInfoFuture.thenAcceptAsync((skuInfoEntity) -> {
            //5、获取spu的规格参数信息  需要spuId
            log.debug("获取spuId={}的规格参数信息",skuInfoEntity.getSpuId());
            List<SpuItemAttrGroupVo> spuItemAttrGroupVos = attrGroupService
                    .getAttrGroupWithAttrsBySpuId(skuInfoEntity.getSpuId(), skuInfoEntity.getCatalogId());
            skuItemVo.setGroupAttrs(spuItemAttrGroupVos);
        }, globalExecutor);

        CompletableFuture<Void> skuImagesFuture = CompletableFuture.runAsync(() -> {
            log.debug("获取skuId={}的图片信息",skuId);
            //2.sku的图片信息    pms_sku_images
            List<SkuImagesEntity> skuImages = skuImagesService.getSkuImagesBySkuId(skuId);
            skuItemVo.setImages(skuImages);
        }, globalExecutor);
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //获取秒杀商品信息
        CompletableFuture<Void> seckillSkuFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            log.debug("获取skuId={}的秒杀信息", skuId);
            R r = seckillFeignService.seckillSkuInfoBySkuId(skuId);
            if (r.getCode() == 0) {
                Optional<SeckillSkuVo> data = r.getData(new TypeReference<SeckillSkuVo>() {
                });
                SeckillSkuVo seckillSkuVo = data.orElse(null);
                if (seckillSkuVo != null) {
                    skuItemVo.setSeckillSkuVo(seckillSkuVo);
                }
            }else{
                log.debug("获取skuId={}的秒杀信息失败,{}", skuId, JSON.toJSONString(r));
            }
        }, globalExecutor);
        CompletableFuture.allOf(future1,future2,future3,skuImagesFuture,seckillSkuFuture).get();
        return skuItemVo;
    }

    @Override
    public List<SkuItemSaleAttrVo> getAllSaleAttrBySpuId(Long spuId) {
        return this.baseMapper.getAllSaleAttrBySpuId(spuId);
    }

}